package com.york.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.york.security.entity.SecurityUser;
import com.york.security.entity.CurrentUserInfo;
import com.york.security.security.JwtUtils;
import com.york.utils.exception.BusinessException;
import com.york.utils.exception.result.R;
import com.york.utils.util.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Description:
 * @Data: 2022/3/22 16:13
 * @Author: yangboxiong
 * @Version
 * @since JDK 1.8
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private JwtUtils jwtUtils;
    private RedisTemplate redisTemplate;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(AuthenticationManager authenticationManager, JwtUtils jwtUtils, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        // 设置登陆路径，并且post请求
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login", "POST"));
    }

    /**
     * 获取表单提交用户名和密码
     *
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        //获取表单提交数据
        try {
            //获取当前实体类对象，读取响应回来的值
            CurrentUserInfo currentUserInfo = new ObjectMapper().readValue(request.getInputStream(), CurrentUserInfo.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(currentUserInfo.getUsername(), currentUserInfo.getPassword(), new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("表单提交有误");
        }

    }


    /**
     * 认证成功调用的方法
     *
     * @param request
     * @param response
     * @param chain
     * @param authResult 认证结果
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //得到认证成功后的用户信息
        SecurityUser user = (SecurityUser) authResult.getPrincipal();
        //根据用户名生成 token
        String username = user.getCurrentUserInfo().getUsername();
        //用户名
        String token = JwtUtils.createToken(username);
        // 把用户名称和用户信息权限列表放到redis中
        redisTemplate.opsForValue().set(username, user.getPermissionValueList());
        //返回 token
        ResponseUtil.out(response, R.ok().data("token", token));
    }

    /**
     * 认证失败调用的方法
     *
     * @param request
     * @param response
     * @param failed
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        ResponseUtil.out(response, R.error());
    }
}
